package org.ru.mse10.cvfpg.generator;

import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.ru.mse10.cvfpg.generator.constants.Attribute;
import org.ru.mse10.cvfpg.generator.constants.Namespace;
import org.ru.mse10.cvfpg.generator.constants.Tag;
import org.ru.mse10.cvfpg.generator.constants.XsltAttributes;
import org.ru.mse10.cvfpg.generator.constants.XsltTags;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public final class DocumentUtil {

	public static void main(String[] args) throws Exception {
		createXsltDocument();
	}

	public static Document createXsltDocument() throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.newDocument();
		Element root = DocumentUtil.createElementNS(document, Namespace.XSLT, XsltTags.STYLESHEET);
		DocumentUtil.setAttribute(root, XsltAttributes.ATTR_VERSION, "1.0");
		document.appendChild(root);
		// serialize(document, System.out);
		return document;
	}

	public static Element createElementNS(Document document, Namespace ns, Tag tag) {
		Element root = document.createElementNS(ns.getNS(), tag.getValue());
		root.setPrefix(ns.getPrefix());
		return root;
	}

	public static Element appendElement(Document document, Element to, Tag tag, Namespace ns) {
		Element element = document.createElement(ns.getPrefix() + ":" + tag.getValue());
		to.appendChild(element);
		return element;
	}

	public static Element appendElementNS(Document document, Element to, Tag tag, Namespace ns) {
		Element element = DocumentUtil.createElementNS(document, ns, tag);
		to.appendChild(element);
		return element;
	}

	public static Element setAttribute(Element element, Attribute attribute, String value) {
		element.setAttribute(attribute.getValue(), value);
		return element;
	}

	public static void serialize(Document doc, OutputStream out) throws Exception {
		TransformerFactory tfactory = TransformerFactory.newInstance();
		Transformer serializer;
		try {
			serializer = tfactory.newTransformer();
			// Setup indenting to "pretty print"
			serializer.setOutputProperty(OutputKeys.INDENT, "yes");
			serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

			DOMSource xmlSource = new DOMSource(doc);
			StreamResult outputTarget = new StreamResult(out);
			serializer.transform(xmlSource, outputTarget);
		} catch (TransformerException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}
